package com.piggy.logi.sys.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.base.Joiner;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.piggy.common.core.constant.SecurityConstants;
import com.piggy.common.core.domain.R;
import com.piggy.common.core.utils.FeignResultUtils;
import com.piggy.common.core.utils.PageUtils;
import com.piggy.common.core.web.page.PagePlus;
import com.piggy.common.core.web.page.TableDataInfo;
import com.piggy.logi.sys.api.domain.LogiSysUser;
import com.piggy.logi.sys.api.vo.LogiLineExtVo;
import com.piggy.logi.sys.api.vo.LogiLineStationExtVo;
import com.piggy.logi.sys.api.vo.LogiSysDeptExtVo;
import com.piggy.logi.sys.bo.LogiLineExtEditBo;
import com.piggy.logi.sys.bo.LogiLineQueryBo;
import com.piggy.logi.sys.bo.LogiSysDeptExtQueryBo;
import com.piggy.logi.sys.domain.LogiLine;
import com.piggy.logi.sys.domain.LogiLineStation;
import com.piggy.logi.sys.mapper.LogiLineMapper;
import com.piggy.logi.sys.mapper.LogiSysDeptExtCusMapper;
import com.piggy.logi.sys.service.ILogiLineService;
import com.piggy.logi.sys.service.ILogiLineStationService;
import com.piggy.logi.sys.service.ILogiSysUserService;
import com.piggy.sys.api.RemoteDistrictService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 线路管理Service业务层处理
 *
 * @author piggy
 * @date 2023-08-14
 */
@Slf4j
@Service
public class LogiLineServiceImpl extends ServiceImpl<LogiLineMapper, LogiLine> implements ILogiLineService {

    @Resource
    private ILogiLineStationService stationService;

    @Resource
    private ILogiSysUserService userService;

    @Resource
    private LogiSysDeptExtCusMapper deptExtCusMapper;

    @Resource
    private RemoteDistrictService districtService;

    @Override
    public LogiLineExtVo queryById(Long lineId) {
        LogiLineExtVo vo = getVoById(lineId, LogiLineExtVo.class);
        if (ObjectUtil.isEmpty(vo)) {
            return null;
        }
        return fillData(Lists.newArrayList(vo)).get(0);
    }

    @Override
    public List<LogiLineExtVo> queryListByIds(List<Long> lineIds) {
        List<LogiLineExtVo> extVoList = listVo(Wrappers.<LogiLine>lambdaQuery().in(LogiLine::getLineId, lineIds), LogiLineExtVo.class);
        return fillData(extVoList);
    }

    @Override
    public TableDataInfo<LogiLineExtVo> queryPageList(LogiLineQueryBo bo) {
        PagePlus<LogiLine, LogiLineExtVo> result = pageVo(PageUtils.buildPagePlus(bo, true), buildQueryWrapper(bo), LogiLineExtVo.class);
        result.setRecordsVo(fillData(result.getRecordsVo()));
        return PageUtils.buildDataInfo(result);
    }

    @Override
    public List<LogiLineExtVo> queryList(LogiLineQueryBo bo) {
        List<LogiLineExtVo> extVoList = listVo(buildQueryWrapper(bo), LogiLineExtVo.class);
        return fillData(extVoList);
    }

    private List<LogiLineExtVo> fillData(List<LogiLineExtVo> extVoList1) {

        List<LogiLineExtVo> extVoList = extVoList1.stream().peek(vo-> {
            if (StrUtil.isBlank(vo.getLineDistrict())) {
                return;
            }
            List<String> distIds = Lists.newArrayList(vo.getLineDistrict().split(","));
            R<Map<String, String>> distNameMap =  districtService.getDistrictMap(distIds, SecurityConstants.INNER);
            FeignResultUtils.throwIfFailed(distNameMap);
            vo.setLineDistrictName(Joiner.on(",").join(ObjectUtil.defaultIfNull(distNameMap.getData(), Maps.newHashMap()).values()));
        }).collect(Collectors.toList());

        LinkedHashMap<Long,LogiLineExtVo> lineMap = extVoList.stream().collect(LinkedHashMap::new, (m, v) -> m.put(v.getLineId(), v), LinkedHashMap::putAll);
        lineMap.put(-1L,new LogiLineExtVo());
        List<LogiLineStationExtVo> stationList = stationService.listVo(new LambdaQueryWrapper<LogiLineStation>().
                in(LogiLineStation::getLineId, lineMap.keySet()).
                orderByAsc(LogiLineStation::getStationFlag), LogiLineStationExtVo.class);

        List<Long> deptIds = stationList.stream().map(LogiLineStationExtVo::getBranchDeptId).distinct().collect(Collectors.toList());
        deptIds.add(-1L);

        List<Long> userIds = stationList.stream().map(LogiLineStationExtVo::getBranchUserId).distinct().collect(Collectors.toList());
        userIds.add(-1L);

        List<LogiSysUser> userList = userService.list(new LambdaQueryWrapper<LogiSysUser>().in(LogiSysUser::getUserId, userIds));
        LinkedHashMap<Long,LogiSysUser> userMap = userList.stream().collect(LinkedHashMap::new, (m, v) -> m.put(v.getUserId(), v), LinkedHashMap::putAll);

        LogiSysDeptExtQueryBo queryBo = (LogiSysDeptExtQueryBo) new LogiSysDeptExtQueryBo().setDeptIdList(deptIds);
        List<LogiSysDeptExtVo> deptList = deptExtCusMapper.extSysDeptList(queryBo);

        LinkedHashMap<Long,LogiSysDeptExtVo> deptMap = deptList.stream().collect(LinkedHashMap::new, (m, v) -> m.put(v.getDeptId(), v), LinkedHashMap::putAll);
        stationList.stream().peek(Any-> {
            Any.setBranchUser(userMap.get(Any.getBranchUserId()));
            Any.setBranchDept(deptMap.get(Any.getBranchDeptId()));
            lineMap.get(Any.getLineId()).getStationList().add(Any);
        }).collect(Collectors.toList());

        lineMap.remove(-1L);
        return new ArrayList<>(lineMap.values());
    }

    @Override
    public LambdaQueryWrapper<LogiLine> buildQueryWrapper(LogiLineQueryBo bo) {
        LambdaQueryWrapper<LogiLine> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getLineId() != null, LogiLine::getLineId, bo.getLineId());
        lqw.like(StrUtil.isNotBlank(bo.getLineName()), LogiLine::getLineName, bo.getLineName());
        lqw.eq(StrUtil.isNotBlank(bo.getLineType()), LogiLine::getLineType, bo.getLineType());
        lqw.eq(StrUtil.isNotBlank(bo.getLineFlag()), LogiLine::getLineFlag, bo.getLineFlag());
        lqw.eq(StrUtil.isNotBlank(bo.getLineScope()), LogiLine::getLineScope, bo.getLineScope());
        lqw.eq(StrUtil.isNotBlank(bo.getLineDirect()), LogiLine::getLineDirect, bo.getLineDirect());
        lqw.eq(StrUtil.isNotBlank(bo.getStatus()), LogiLine::getStatus, bo.getStatus());
        lqw.eq(bo.getTotalMile() != null, LogiLine::getTotalMile, bo.getTotalMile());
        lqw.eq(bo.getTotalTime() != null, LogiLine::getTotalTime, bo.getTotalTime());

        if (StrUtil.isBlank(bo.getLineDistrict())) {
            return lqw;
        }

        String findSQL = "";
        String[] distIds = bo.getLineDistrict().split(",");
        for(String distId : distIds) {
            findSQL += StrUtil.isBlank(distId) ? "" : (StrUtil.isBlank(findSQL) ? " FIND_IN_SET ('"+distId+"',line_district)" : " OR FIND_IN_SET ('"+distId+"',line_district)");
        }
        lqw = lqw.apply(StrUtil.isNotBlank(findSQL), "(" + findSQL + ")");

        return lqw;

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public LogiLineExtVo insertByAddBo(LogiLineExtEditBo bo) {
        LogiLine add = BeanUtil.toBean(bo, LogiLine.class);
        save(add);
        if (CollUtil.isNotEmpty(bo.getStationList())) {
            bo.getStationList().forEach(t-> t.setLineId(add.getLineId()));
            stationService.batchByAddBo(bo.getStationList());
        }
        return queryById(add.getLineId());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public LogiLineExtVo updateByEditBo(LogiLineExtEditBo bo) {
        LogiLine update = BeanUtil.toBean(bo, LogiLine.class);
        updateById(update);
        if (CollUtil.isNotEmpty(bo.getStationList())) {
            bo.getStationList().forEach(Any-> {
                Any.setLineId(bo.getLineId());
                Any.setId(null);
            });
            stationService.batchByUpdateBo(bo.getStationList());
        }
        return queryById(update.getLineId());
    }

    @Override
    public int getLineNums(String distId) {
        LambdaQueryWrapper<LogiLine> lambdaQueryWrapper = Wrappers.<LogiLine>lambdaQuery().apply(1 ==1,"FIND_IN_SET ('"+distId+"',line_district)");
        return (int)this.count(lambdaQueryWrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return removeByIds(ids);
    }

    @Override
    public List<LogiLineExtVo> selectGeoDeptList(BigDecimal lng, BigDecimal lat) {
        return stationService.selectGeoDeptList(lng, lat);
    }

}
